using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace AdminSecurity.Extensions
{
   public class AppRequirement(IServiceProvider serviceProvider) : AuthorizationHandler<AppRequirement>, IAuthorizationRequirement
{
    private readonly ISecutityAdminService _securityAdminService = serviceProvider.GetRequiredService<ISecutityAdminService>();
    private readonly IConfiguration _configuration = serviceProvider.GetRequiredService<IConfiguration>();


    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AppRequirement requirement)
    {
        // 检查用户是否已登录
        // if (context.User.Identity?.IsAuthenticated != true)
        // {
        //     return Task.CompletedTask;
        // }

        // // 如果用户是管理员，直接通过
        // if (context.User.IsInRole("Administrator"))
        // {
        //     context.Succeed(requirement);
        //     return Task.CompletedTask;
        // }

        // // 获取当前用户和应用 ID
        // var userName = context.User.Identity.Name;
        // var appId = _configuration["AppId"];

        // if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(appId))
        // {
        //     return Task.CompletedTask;
        // }

        // try
        // {
        //     // 检查用户是否有访问应用的权限
        //     var userApps = _securityAdminService.GetApps(userName);
        //     if (userApps.Any(a => a == appId))
        //     {
        //         context.Succeed(requirement);
        //     }
        // }
        // catch (Exception ex)
        // {
        //     // 记录异常日志（根据需要替换为实际的日志记录）
        //     Console.WriteLine($"AppRequirement: 权限验证失败 - {ex.Message}");
        // }

        return Task.CompletedTask;
    }
}
}